RDBMS | MongoDB |
---|---|
Database | Database |
Table | Collection - JS object like syntax |
Row (record) | Document (record) - JS object, i.e., JSON, like syntax |
Column | Field |
Primary key | Default key '_id' provided by MongoDB itself |
SQL | JS like syntax (But the idea is not much different.) |
/etc/mongod.conf
.
security: authorization: enabled
$ mongo admin -u root -p MaongoDB shell ... Enter password: > db.createRole( { role: "changeOwnPasswordCustomDataRole", privileges: [ { resource: { db: "", collection: ""}, actions: [ "changeOwnPassword", "changeOwnCustomData" ] } ], roles: [] } ) > exit $ mongo admin -u root -p MaongoDB shell ... Enter password: use dbname > db.createUser( { user: "???", pwd: "???", roles: [ "readWrite", { role: "changeOwnPasswordCustomDataRole", db: "admin" } ] } ) > exit $ mongo dbname -u username -p MaongoDB shell ... Enter password: > db.runCommand( { updateUser: "test", pwd: "newpassword" } )
$ mongo databasename -u username -p $ mongo [admin] -u root -p $ mongo COMP4620_test -u test -p
$ mongo databasename -u username -p $ mongo COMP4620_yourMongoDBusername -u yourMongoDBusername -p
db // List the current working database use mydb // Change the current working database; db represents the current working database help show collections // Show all the collections in db j = { name: 'mongo' } k = { x: 3, y: j.name } // j.name? db.testData.insertOne(j) // A collection, testData, will be created if it doest not exist db.testData.insertOne(j) // The same document again? db.testData.insertOne(k) db.testData.insertOne({course: "COMP4620", user: "Tom"}) db.testData.find() db.testData.find({user:"Tom"}) db.testData.drop() db.createCollection('Users') show collections exit
db.collection.findOne()
, db.collection.find()
db.collection.find(...query_criteria...)...modifier...;
query_criteria is like a document.db.collection.insertOne(...document...)
, .insertMany(...)
db.collection.updateOne(...document...)
, .updateMany(...)
db.collection.deleteOne(...document...)
, .deleteMany(...)
RDBMS | MongoDB |
---|---|
insert | insertOne(), insertMany() |
select | findOne(), find() |
update | updateOne(), updateMany() |
delete | deleteOne(), deleteMany() |
db.Users.insertOne({username: '...', password: '...', full_name: '...', email: '...'})
.insertMany([{...}, ...])
.find()
return?.find()
and .findOne()
are different?.find()
?db.Users.findOne({username: '...', password: '...'})
db.Users.find({username: {$exists: true}})
db.Users.find({username: {$regex: /^a/}}) // not in JavaScript? db.Users.find({username: /a$/}) // not in JavaScript? db.Users.find({username: {$regex: '^a'}}) db.Memos.find({memo: {$regex:`${search_term}`, $options:'i'}})
db.inventory.find({$or: [{quantity: {$gt: 20}}, {price: {$lte: 29.99}}]})
db.inventory.find({quantity: {$gt: 20}}, {price: {$lte: 29.99}}) // You can also use $and.
db.inventory.find({quantity: {$gt: 20}}, {price: {$lte: 29.99}}).sort({name: 1}) // 1: ascending order; -1: descending order
db.Users.updateMany({username: '...'}, {$set: {password: '...'}})
$rename
update operator$unset
operator
db.Users.deleteMany({username: '...'})
db.collection.drop()
db.dropDatabase()
node_modules
, does not exist, create it.$ mkdir node_modules
node_modules
in the current working directory.$ npm install mongodb@4.17.2
node_modules
readable to all accounts on cs.tru.ca as follows.
It is necessary when sjs programs are executed from the client-side using the instructor's Node Web Server of port number 8080.$ ~mlee/bin/chr node_modules
mongodb://username:password@server[:port]/databasename
, to make a connection.
const MongoClient = require('mongodb').MongoClient; // mongodb://username:password@server[:port]/databasename MongoClient.connect('mongodb://???:???@127.0.0.1:27017/???', function(err, conn) { // What is '127.0.0.1'? Any security issue? // conn is a connection stub used for CRUD operations. if(err) throw err; console.log("MongoDB connected"); // What if conn.close() is here? conn.close(); });
const MongoClient = require('mongodb').MongoClient; (??? function() { try { const conn = ??? MongoClient.???('mongodb://youraccount:password@127.0.0.1:27017/yourdbname'); console.log("MongoDB connected"); conn.close(); } catch(err) { console.log(err); } })(); // self invocation of an anonymous function
const MongoClient = require('mongodb').MongoClient;
const ??? = ??? function(_GET, _POST, callback) { // This function should pass a string message back through callback.
try {
// mongodb://username:password@127.0.0.1[:port]/databasename
const conn = ??? MongoClient.???("mongodb://????@127.0.0.1:27017/???");
conn.???(); // It is a must. Otherwise, the max number of connections will be fed up. Why?
???("MongoDB connected using async/await");
}
catch(err) {
callback('Connection error');
}
}
????
conn
stub from MongoClient.connect(...)
db
stub from conn.db()
db.collection(...)
collection
stubconst MongoClient = require('mongodb').MongoClient; (async function() { try { // connection stub const conn = await MongoClient.connect(????); console.log("MongoDB connected"); // db stub let db = conn.???(); // If the "Users" collection does not exist, let's create it. let list = await db.listCollections().toArray(); let exist = false; for (let i = 0; i < list.length; i++) { if (list[i].name == "Users") { exist = true; break; } } if (!exist) { await db.createCollection("Users"); console.log("Users created"); } else console.log("Users exists"); // collectin stub let collection = db.???("Users"); // find all documents in the collection let lists = await collection.????.toArray(); console.log(lists); // close the connection to MongoDB conn.close(); } catch(err) { console.log(err); conn.close(); } })(); // self invocation of an anonymous function
collection.insertOne|insertMany(..., {w:1}, function(err, result) { ... })
// the w option to request acknowledgment; See Write Concern for {w:1}.
collection.findOne(..., function(err, item) { ... });
collection.find(...).toArray(function(err, items) { ... });
collection.updateOne|updateMany(..., {$set:...}, {w:1}, function(err, result) { ... });
collection.deleteOne|deleteMany(..., {w:1}, function(err, result) { ... });
const MongoClient = require('mongodb').MongoClient; const usernameExists = ??? function(???, callback) { ???? let collection = db.???("Users"); let list = ??? ????(????); if (????) callback(true); else callback(false); conn.close(); } // code to test the above function let username = "tom"; usernameExists(???, function(result) { console.log("tom: " + result); }); username = "john"; usernameExists(???, function(result) { console.log("john: " + result); });
const MongoClient = require('mongodb').MongoClient; const registerUser = ??? function(???, ???, callback) { try { ???? let collection = db.collection("Users"); ??? ???.???(????); ???? conn.close(); } catch(err) { callback(false); conn.close(); }; } // code to test the above function registerUser("john", "topoftheworld", ???? { console.log(result); });
const MongoClient = require('mongodb').MongoClient; const validateUsernamePassword = ??? function(username, password, callback) { ???? let list = ??? ????(????); // findOne() or find().toArray() if (????) callback(true); else callback(false); conn.close(); } // code to test the above function let username = "tom"; let password = "topsecretpassword"; validateUsernamePassword(???, ???, function(result) { console.log("tom: " + result); }); username = "john"; password = "topoftheworld"; validateUsernamePassword(???, ???, function(result) { console.log("john: " + result); });
const deleteUser = ??? (username, callback) => // You need to include the next code with the connection to MongoDB. { ???? ???? // deleteOne() or deleteMany() let list = ??? ????(????); // findOne() for testing if (????) callback(true); else callback(false); conn.close(); } let username = "tom"; deleteUser(???, function(result) { console.log(result); });
usernameExists()
, registerUser()
, validateUsernamePassword()
, updateUser()
, and deleteUser()
that were developed in multiple previous Trials? $(document).ready(function() { ... });
.model
is required from chat_model.js, and this module has a method ready()
.
When the model
is ready (i.e., ready()
passes true back,) the methods in UserManagement can be invoked.
Any idea how to use read()
?
// In chat_controller.sjs program, how to use chat_model.js? // If Model were revised, the cached Model module may need to be deleted. delete require.cache[require.resolve("./chat_model.js")]; const model = require("./chat_model.js"); const proceed = function(_GET, _POST, callback) { ... // For Join model.ready(function(result) { if (result) model.usernameExists(_POST['username', function(result) { ... }); }); ... // For SignIn model.ready(function(result) { if (result) model.validateUsernamePassword(_POST['username'], _POST['password'], function(result) { if(result) callback("true"); else callback("false"); }); }); ... model.close(); // It is required. ... } ...
// All functions pass back a Boolean value - true or false. let MongoClient; let conn; // connection stub let db; // db stub let collection; // collection stub let connected = false; // flag to see if a connection is made // Prepares conn, db, collecton, connected // Passes true|false back through a callback function const ready = async function(callback) { if (???) callback(true); else { try { // connection MongoClient = require("mongodb").MongoClient; conn = await MongoClient.connect(????); // db stub db = ????; /* It is unnecessary. // If the "Users" collection does not exist, let's create it. let list = await db.listCollections().toArray(); let exist = false; for (let i = 0; i < list.length; i++) { if (list[i].name == "Users") { exist = true; break; } } if (!exist) await db.createCollection("Users"); */ // collection stub collection = ????("Users"); // return ... through the callback function ???? callback(???); } catch(err) { connected = false; callback(false); } } } const close = function() { if (???) { connected = ???; conn.close(); } } const usernameExists = ??? function(u, callback) { try { let list = ???? if (????) callback(true); else callback(false); } catch(err) { callback(false); } } ???? exports.ready = ready; exports.close = close; exports.usernameExists = usernameExists; exports.registerUser = registerUser; exports.validateUsernamePassword = validateUsernamePassword; exports.updateUser = updateUser; exports.deleteUser = deleteUser;
... let timerid; const ready = async function(callback) { if (connected) callback(true); else { try { // connection MongoClient = require("mongodb").MongoClient; conn = await MongoClient.connect(????); // 1 second timer to close ???? // clear the timer timerid = ???(() => { // re-start the timer close(); }, 1000); ... } catch(err) { ... } } } const close = function() { if (connected) { conn.close(); connected = false; // clear the timer ???(timerid); } }
var crypto = require('crypto'); // create hmac var hash = crypto.createHmac('sha512', 'topsecretkey'); // sha1, md5, sha256, sha512, ... // It requires a key. // Is it a good idea for your chatting program? hash.update('Good morning, Dave!'); hash.update('Good morning, HAL!'); var value = hash.digest('hex'); // hex, binary, or base64 // print result console.log(value);
var crypto = require('crypto'); // create hash var hash = crypto.createHash('sha512'); // sha1, md5, sha256, sha512, ... // No key is required. // How to use this for your chatting program? hash.update('Good morning, Dave!'); hash.update('Good morning, HAL!'); var value = hash.digest('hex'); // hex, binary, or base64 // print result console.log(value);
db.close(); // When do you close?